package com.example.demo.blockqueue;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2021年01⽉21⽇<br/>
 * @version：v1.0.0<br>
 */
public class DelayQuueDemo {

    private static DelayQueue<DelayTask> delayQueue = new DelayQueue<>();
    private static AtomicInteger atomicInteger = new AtomicInteger(1);
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int delayTime = 3;
                long milliLong = 0L;
                for (int i = 0; i < 5; i++) {
                    if(i == 0){
                        milliLong = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                    }
                    int andIncrement = atomicInteger.getAndIncrement();
                    System.out.println("【生产者】放入数据....任务-【" + andIncrement + "】当前时间:" + simpleDateFormat.format(System.currentTimeMillis()));
                    DelayTask task = new DelayTask("任务-【" + andIncrement + "】", milliLong, delayTime, TimeUnit.SECONDS);
                    delayQueue.add(task);
                    milliLong = DelayTask.getDelayTime(milliLong, delayTime, TimeUnit.SECONDS);
                }
            }
        }).start();

//        try {
//            TimeUnit.SECONDS.sleep(1);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        DelayTask take = delayQueue.take();
                        System.out.println("【消费者】取出数据...." + take.getTaskName() + "当前时间:" + simpleDateFormat.format(System.currentTimeMillis()));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
